package com.laowang.project.monitor.mapper;

import com.laowang.common.utils.StringUtils;
import com.laowang.project.monitor.domain.SysOperLog;
import com.laowang.project.monitor.form.SysOperLogForm;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.ibatis.annotations.Update;
import tk.mybatis.mapper.additional.idlist.DeleteByIdListMapper;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.entity.Example;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 操作日志 数据层
 * 
 * @author laowang
 */
public interface SysOperLogMapper extends Mapper<SysOperLog>, DeleteByIdListMapper<SysOperLog, Long>
{
    /**
     * 新增操作日志
     * 
     * @param operLog 操作日志对象
     */
    default void insertOperlog(SysOperLog operLog) {
        operLog.setOperTime(new Date());
        insert(operLog);
    }

    /**
     * 查询系统操作日志集合
     * 
     * @param param 操作日志对象
     * @return 操作日志集合
     */
    default List<SysOperLog> selectOperLogList(SysOperLogForm param) {
        Example example = new Example(SysOperLog.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotEmpty(param.getTitle())) {
            criteria.andLike("title", "%" + param.getTitle() + "%");
        }
        if (Objects.nonNull(param.getBusinessType())) {
            criteria.andEqualTo("businessType", param.getBusinessType());
        }
        if (ArrayUtils.isNotEmpty(param.getBusinessTypes())) {
            criteria.andIn("businessType", Arrays.asList(param.getBusinessTypes()));
        }
        if (Objects.nonNull(param.getStatus())) {
            criteria.andEqualTo("status", param.getStatus());
        }
        if (StringUtils.isNotEmpty(param.getOperName())) {
            criteria.andLike("operName", "%" + param.getOperName() + "%");
        }
        if (StringUtils.isNotEmpty(param.getBeginTime())) {
            criteria.andCondition("date_format(oper_time, '%y%m%d') >= date_format('" + param.getBeginTime() + "', '%y%m%d')");
        }
        if (StringUtils.isNotEmpty(param.getEndTime())) {
            criteria.andCondition("date_format(oper_time, '%y%m%d') <= date_format('" + param.getEndTime() + "', '%y%m%d')");
        }
        example.orderBy("operId").desc();
        return selectByExample(example);
    }

    /**
     * 清空操作日志
     */
    @Update("truncate table sys_oper_log")
    void cleanOperLog();
}
